<template>
  <a-modal
    title="编辑图片"
    :width="600"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    okText="确认"
    cancelText="取消"
  >
    <a-row :gutter="24" v-if="visible">
      <a-col :md="18">
        <vue-cropper
          ref="cropper"
          preview=".preview"
          :auto-crop="true"
          :view-mode="1"
          :auto-crop-area="1"
          :min-container-width="100"
          :min-container-height="100"
          :aspect-ratio="1"
          :src="image"
          :container-style="{ 'width': '100%', 'height': '400px' }"
          :img-style="{ 'max-width': '100%', 'max-height': '100%' }"
          :class="image === '' ? 'loading' : 'loaded'"
          @crop="changeCrop"/>
      </a-col>
      <a-col :md="6">
        <img class="previewBox" :src="cropImg" />
      </a-col>
    </a-row>
  </a-modal>
</template>

<script>
  import VueCropper from 'vue-cropperjs'
  import 'cropperjs/dist/cropper.css'
  export default {
    name: 'EditImage',
    components: {
      VueCropper
    },
    data () {
      return {
        visible: false,
        confirmLoading: false,
        image: '',
        containerStyle: {
          width: '100%',
          border: 'solid'
        },
        fileName: '',
        cropImg: ''
      }
    },
    methods: {
      edit (imageUrl, fileName) {
        this.visible = true
        this.image = imageUrl
        this.fileName = fileName
      },
      changeCrop () {
        if (this.$refs.cropper !== undefined) {
          this.cropImg = this.$refs.cropper.getCroppedCanvas().toDataURL('image/jpeg')
        }
      },
      handleSubmit () {
        this.cropImg = this.$refs.cropper.getCroppedCanvas().toDataURL('image/jpeg')
        this.$emit('ok', this.cropImg)
        this.reset()
      },
      handleCancel () {
        this.reset()
      },
      reset () {
        this.image = ''
        this.fileName = ''
        this.visible = false
        this.cropImg = ''
      }
    }
  }
</script>

<style lang="less" scoped>
  .previewBox {
    box-shadow: 0 0 5px #adadad;
    width: 90%;
    height: 90%;
    margin-top: 30px;
    overflow: hidden;       /*这个超出设置为隐藏很重要，否则就会整个显示出来了*/
  }
</style>
